<template>
  <div class="user-table">
    <div class="table-header">
      <span>用户列表</span>
      <div class="header-actions">
        <el-button v-if="showSelectAll" link type="primary" @click="handleSelectAll">全选</el-button>
        <el-button v-if="showClearAll" link type="danger" @click="handleUnselectAllPage">取消全选</el-button>
      </div>
    </div>
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="data"
      height="calc(100vh - 240px)"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="multiple" :reserve-selection="true" :selectable="isSelectable" type="selection" width="55" />
      <el-table-column v-else width="55">
        <template #default="{ row }">
          <el-radio v-model="selectedId" :label="row.id" @change="handleRadioChange(row)" />
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="name" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="user-info">
            <el-avatar :size="32" :src="row.avatar">
              {{ row.name?.charAt(0) }}
            </el-avatar>
            <span>{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="mobile" show-overflow-tooltip />
      <el-table-column v-if="showActions" fixed="right" label="操作" width="80">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleViewDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-footer">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        background
        class="custom-pagination"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ElTable } from 'element-plus'
import { computed, nextTick, ref, watch } from 'vue'
import type { User } from '../types'

const props = defineProps<{
  data: User[]
  loading: boolean
  multiple?: boolean
  showActions?: boolean
  total: number
  selectedUsers?: User[]
}>()

const emit = defineEmits<{
  (e: 'selection-change', users: User[]): void
  (e: 'select-all'): void
  (e: 'view-detail', user: User): void
  (e: 'page-change', page: number): void
  (e: 'size-change', size: number): void
}>()

// 表格引用
const tableRef = ref<InstanceType<typeof ElTable>>()

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 单选模式
const selectedId = ref<string>('')

// 暂时禁用selection-change事件处理，防止无限循环
const disableSelectionChange = ref(false)

// 计算属性
const showSelectAll = computed(() => !!props.multiple && props.data.length > 0)
const showClearAll = computed(() => !!props.multiple && props.selectedUsers && props.selectedUsers.length > 0)

// 表格加载完成后同步选中状态
watch(
  () => props.data,
  () => {
    if (props.multiple && tableRef.value && props.selectedUsers && props.selectedUsers.length > 0) {
      nextTick(() => {
        syncSelectedStatus()
      })
    }
  },
  { immediate: true }
)

// 监听selectedUsers变化，更新表格选中状态
watch(
  () => props.selectedUsers,
  (newVal) => {
    if (props.multiple && tableRef.value && newVal) {
      syncSelectedStatus()
    }
  },
  { deep: true }
)

// 同步选中状态到表格
const syncSelectedStatus = () => {
  if (!tableRef.value || !props.selectedUsers) return

  disableSelectionChange.value = true

  // 先清除所有选中
  tableRef.value.clearSelection()

  // 再设置选中状态
  props.selectedUsers.forEach((user) => {
    const rowIndex = props.data.findIndex((item) => item.id === user.id)
    if (rowIndex !== -1) {
      tableRef.value?.toggleRowSelection(props.data[rowIndex], true)
    }
  })

  setTimeout(() => {
    disableSelectionChange.value = false
  }, 0)
}

// 判断是否可选
const isSelectable = () => {
  return true
}

// 选择变化
const handleSelectionChange = (selection: User[]) => {
  console.log('[UserTable] handleSelectionChange emitted:', JSON.stringify(selection))
  if (disableSelectionChange.value) return
  emit('selection-change', selection)
}

// 单选变化
const handleRadioChange = (user: User) => {
  console.log('[UserTable] handleRadioChange emitted:', JSON.stringify([user]))
  emit('selection-change', [user])
}

// 全选
const handleSelectAll = () => {
  if (!tableRef.value) return

  // 先清空当前选择
  tableRef.value.clearSelection()

  // 然后全选当前页
  nextTick(() => {
    // 直接选中当前页所有行
    props.data.forEach((row) => {
      tableRef.value?.toggleRowSelection(row, true)
    })

    // 发送全选事件，确保checkUser接收到完整的当前页数据
    emit('select-all')
    emit('selection-change', [...props.data])
  })
}

// 取消当前页全选 (原 handleClearAll)
const handleUnselectAllPage = () => {
  if (!tableRef.value) return

  // 1. 清除表格当前页的选中状态
  tableRef.value.clearSelection()

  // 2. 从总的已选用户中移除当前页的用户
  // 我们需要 props.selectedUsers (总的已选) 和 props.data (当前页数据)
  if (props.selectedUsers && props.selectedUsers.length > 0) {
    const currentPageUserIds = new Set(props.data.map((user) => user.id))
    const usersToKeep = props.selectedUsers.filter((user) => !currentPageUserIds.has(user.id))
    emit('selection-change', usersToKeep) // 发送移除了当前页用户后的列表
  } else {
    // 如果原本就没有已选用户，或者 selectedUsers 未定义，则发送空数组
    emit('selection-change', [])
  }
}

// 查看详情
const handleViewDetail = (user: User) => {
  emit('view-detail', user)
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  emit('size-change', size)
}

// 页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  emit('page-change', page)
}
</script>

<style scoped>
.user-table {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  font-weight: 500;
  color: #333;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.user-info {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  background-color: #f8f9fa;
  border-top: 1px solid #ebeef5;
  border-radius: 0 0 8px 8px;
}

.custom-pagination {
  margin: 0 auto;
}

:deep(.el-table) {
  flex: 1;
  border: none;
  border-radius: 0;
}

:deep(.el-table__header) {
  background-color: #f8f9fa;
}

:deep(.el-table__body-wrapper) {
  overflow-x: hidden;
}

:deep(.el-button--link) {
  font-weight: 500;
}

:deep(.el-avatar) {
  font-weight: 500;
  color: white;
  background-color: var(--el-color-primary);
}
</style>
